package base.thread_JUC2.chapter01.demo007;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Deque;
import java.util.concurrent.TimeUnit;

/**
 * 管理队列中写入的Event对象，如果Event创建时间已经有10s了，就从队列里删除该事件。（守护线程）
 */
public class CleanerTask extends Thread {

    private Deque<Event> deque ;

    public CleanerTask(Deque<Event> deque) {
        this.deque = deque;
        // 设置为守护线程
        setDaemon(true);
    }

    @Override
    public void run() {
        while (true){

            if (deque.size()==0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                continue;
            }

            long seconds ;
            boolean delete = false;
            do {
                LocalDateTime now = LocalDateTime.now();
                /** 检查当前时间和队列最后一个Event的创建时间是否相差超过10s；
                 * 删除队列中相差超过10s的Event。
                 */
                Event event = deque.getLast();
                seconds = Duration.between(event.getNow(), now).getSeconds();

                if (seconds > 10) {
                    System.out.printf("Clean: %s \n", event.getEvent());
                    deque.removeLast();
                    delete = true;
                }
            }while (seconds > 10);

            if (delete) {
                System.out.printf("Size of the queue: %d\n", deque.size());
            }
        }
    }


}
